﻿using System;
using System.IO;
using System.Windows.Forms;
using EnvDTE;

namespace SPDevExplorer
{
    public partial class SiteExplorer
    {
        private void mnuOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFile(_ctlExplorerTree.SelectedNode);
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuDeleteFile_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode fileNode = _ctlExplorerTree.SelectedNode;

                if (_ctlExplorerTree.SelectedNode != null)
                {
                    FileProperties p = new FileProperties(fileNode);
                    DialogResult result =
                        MessageBox.Show(String.Format("Are you sure you want to delete file '{0}'?", p.Name),
                                        "Confirm Delete", MessageBoxButtons.OKCancel);
                    if (result == DialogResult.OK)
                    {
                        TreeNode parentFolderNode = fileNode.Parent;

                        // Make next node the current node after deletion, or prev is no next
                        string currentNodeText = null;
                        if (fileNode.NextNode != null)
                        {
                            currentNodeText = fileNode.NextNode.Text;
                        }
                        else if (fileNode.PrevNode != null)
                        {
                            currentNodeText = fileNode.PrevNode.Text;
                        }

                        string sPath = FileNodeToWorkingFolderFilePath(fileNode);

                        if (DTE.ItemOperations.IsFileOpen(sPath, EnvDTE.Constants.vsViewKindAny))
                        {
                            Window w = _windows[sPath];
                            w.Activate();
                            // Close the document currently open in Visual Studio, don't need to save
                            w.Document.Close(vsSaveChanges.vsSaveChangesNo);
                        }

                        DeleteFile(fileNode);

                        RefreshFolder(parentFolderNode, currentNodeText);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEvent("Can't delete the selected file.", ex);
            }
        }

        private void mnuFileInfo(object sender, EventArgs e)
        {
            try
            {
                TreeNode selectedFile = _ctlExplorerTree.SelectedNode;
                FileProperties fp = new FileProperties(selectedFile);
                MessageBox.Show(fp.Xml.OuterXml, String.Format("Information on file '{0}'", fp.Name),
                                MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                LogEvent("Can't get information on the selected file", ex);
            }
        }


        private void mnuRenameFile_Click(object sender, EventArgs e)
        {
            _ctlExplorerTree.SelectedNode.BeginEdit();
        }

        private void mnuCopyFile_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode selectedFile = _ctlExplorerTree.SelectedNode;
                FileProperties fp = new FileProperties(selectedFile);
                TreeNode parentFolderNode = selectedFile.Parent;

                string fileUrl = fp.Url;
                string filename = fp.Name;
                string copyFilename = Path.GetFileNameWithoutExtension(filename) + "-copy" + Path.GetExtension(filename);

                DevServices(selectedFile).CopyFile(fileUrl, copyFilename);
                // MessageBox.Show(String.Format("Copied file '{0}' to file '{1}', including its properties", filename, copyFilename), "Copy File", MessageBoxButtons.OK);
                RefreshFolder(parentFolderNode, copyFilename,
                    newFileNode =>
                    {
                        if (newFileNode != null)
                        {
                            // Checkout the new created node, and let the user modify the filename
                            CheckoutFile(newFileNode);
                            newFileNode.BeginEdit();
                        }
                    }
                );
            }
            catch (Exception ex)
            {
                LogEvent("Can't copy the selected file.", ex);
            }
        }

        private void mnuSaveFile_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode fileNode = _ctlExplorerTree.SelectedNode;
                string sPath = FileNodeToWorkingFolderFilePath(fileNode);

                FolderProperties fp = new FolderProperties(fileNode.Parent);

                if (fp.IsSystem)
                {
                    MessageBox.Show("A system file can't be saved", "Error");
                    return;
                }

                if (DTE.ItemOperations.IsFileOpen(sPath, EnvDTE.Constants.vsViewKindAny))
                {
                    Window w = _windows[sPath];
                    w.Activate();
                    // Save the document currently open in Visual Studio, should trigger save to SharePoint as well
                    w.Document.Save(sPath);
                }
                else
                {
                    // Document not open in Visual Studio, explicitly save working folder version to SharePoint
                    SaveFileFromWorkingFolderToSharePoint(fileNode);
                }
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuCheckOutFile_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode fileNode = _ctlExplorerTree.SelectedNode;
                CheckoutFile(fileNode);

                FileProperties p = new FileProperties(fileNode);
                string sPath = FileNodeToWorkingFolderFilePath(fileNode);
                if (DTE.ItemOperations.IsFileOpen(sPath, EnvDTE.Constants.vsViewKindTextView))
                {
                    Window w = _windows[sPath];
                    w.Activate();
                }
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuCheckInFile_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode fileNode = _ctlExplorerTree.SelectedNode;
                FileProperties p = new FileProperties(fileNode);

                if (p.HasCheckedOut)
                {
                    ReplaceFileNode(p, DevServices(fileNode).CheckinFile(p.Url));

                    //string sFile = DevServices(_ctlExplorerTree.SelectedNode).GetFile(p.Url);
                    string sPath = FileNodeToWorkingFolderFilePath(fileNode);

                    if (DTE.ItemOperations.IsFileOpen(sPath, EnvDTE.Constants.vsViewKindTextView))
                    {
                        FileInfo fi = new FileInfo(sPath);
                        fi.IsReadOnly = true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuUndoCheckout_Click(object sender, EventArgs e)
        {
            try
            {
                FileProperties p = new FileProperties(_ctlExplorerTree.SelectedNode);

                if (p.HasCheckedOut &&
                    MessageBox.Show("Undo the checkout and loose all changes.\n\nAre your sure?", "Undo CheckOut",
                                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string sXML = DevServices(_ctlExplorerTree.SelectedNode).UndoCheckoutFile(p.Url);
                    ReplaceFileNode(p, sXML);
                }
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuPublishFile_Click(object sender, EventArgs e)
        {
            try
            {
                FileProperties p = new FileProperties(_ctlExplorerTree.SelectedNode);
                ReplaceFileNode(p, DevServices(_ctlExplorerTree.SelectedNode).Publish(p.Url));
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuApproveFile_Click(object sender, EventArgs e)
        {
            try
            {
                FileProperties p = new FileProperties(_ctlExplorerTree.SelectedNode);
                ReplaceFileNode(p, DevServices(_ctlExplorerTree.SelectedNode).Approve(p.Url));
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuPublishAndApproveFile_Click(object sender, EventArgs e)
        {
            try
            {
                FileProperties p = new FileProperties(_ctlExplorerTree.SelectedNode);
                ReplaceFileNode(p, DevServices(_ctlExplorerTree.SelectedNode).PublishAndApprove(p.Url));
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuRefreshFile_Click(object sender, EventArgs e)
        {
            try
            {
                RefreshFileDetails(_ctlExplorerTree.SelectedNode);
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }


        private void mnuNewFile_Click(object sender, EventArgs e)
        {
            try
            {
                FolderProperties fp = new FolderProperties(_ctlExplorerTree.SelectedNode);
                int iCount = 1;
                foreach (TreeNode oNode in _ctlExplorerTree.SelectedNode.Nodes)
                {
                    string sText = oNode.Text.ToLower();
                    if (sText.StartsWith("newfile") && sText.EndsWith(".txt")) iCount++;
                }

                TreeNode oNew = CreateFile(_ctlExplorerTree.SelectedNode, "NewFile" + iCount.ToString() + ".txt", fp);
                oNew.BeginEdit();
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }

        private void mnuFileSPWebPartPageMaintenance_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode node = _ctlExplorerTree.SelectedNode;
                string nodeUrl = FullUrlOfNode(node) + "?contents=1";
                DTE.ItemOperations.Navigate(nodeUrl, vsNavigateOptions.vsNavigateOptionsDefault);
            }
            catch (Exception ex)
            {
                LogEvent(ex);
            }
        }
    }
}